import React, { Component } from 'react';
import { base,  createPage,getMultiLang } from 'nc-lightapp-front';
const { NCTabs: Tabs, NCTable: Table, NCCheckbox: Checkbox, NCDiv} = base;
// const { NCTabPane: TabPane } = Tabs;
import TransSortPermTreeRef from '../../../refer/voucher/TransSortPermTreeRef/index';
import { onButtonClick, initTemplate } from '../syncTree/events';

class SelfDocTable extends Component {
	constructor(props) {
		super(props);
		this.state = {
			tableData: [], //表格数据
			pk_accountingbook:'',
			checkedAll: false, //是否全选
			selectData: [], //选中数据
			selIds: [], //选中行号
			checkedArray: [
				//各行选中判断
			],
			configs: {}, //人员参照
			checkedData: [], //选中数据
			json: {}
		};
	}
	getColumns = (json) => {
		let { tableData, pk_accountingbook } = this.state
		const emptyCell = <span>&nbsp;</span>
		let columns = [
			{
				title: (<div fieldid='index'>{json['20020SDTCD-000020']}</div>),/* 国际化处理： 序号*/
				dataIndex: 'index',
				key: 'index',
				width: '100px',
				render: (text, record, index) => <div fieldid='index'>{index+1 ? index+1 : emptyCell}</div>
			},
			{
				title: (<div fieldid='m_transprojectcode'>{json['20020SDTCD-000021']}</div>),/* 国际化处理： 编号*/
				dataIndex: 'm_transprojectcode',
				key: 'm_transprojectcode',
				width: '160px',
				render: (text, record, index) => <div fieldid='m_transprojectcode'>{tableData[index].code ? tableData[index].code: emptyCell}</div>
			},
			{
				title: (<div fieldid='m_transprojectname'>{json['20020SDTCD-000022']}</div>),/* 国际化处理： 名称*/
				dataIndex: 'm_transprojectname',
				key: 'm_transprojectname',
				width: '160px',
				render: (text, record, index) => {
					// let {pk_accountingbook,tableData} = this.state
					let {user, role} = tableData[index];
					if(!user || !user.value){
						user = role;
					}
					return(
						<div fieldid='m_transprojectname'>
							<TransSortPermTreeRef
										value={[{
										refname: user && user.display,
										refpk: user && user.value,
										values: {nodeType: user && user.nodeType},
										refcode: user && user.refcode
									}]}
									fieldid='m_transprojectname'
									isMultiSelectedEnabled = {true}
									disabled={ this.props.addStatus}
									onlyLeafCanSelect={true}  //是否只有叶子节点可选
									queryCondition={ function() {
										
										let condition = {
											pk_accountingbook: pk_accountingbook,
											"isDataPowerEnable": 'Y',
											"DataPowerOperationCode" : 'fi'
										};
										return condition;
									}}
									onChange={(v) => {
										this.props.handleTableDataChange(index, v);
									}}
								
							/>
						</div>
					)
				}
			},
			{
				title: (<div fieldid='m_memo'>{json['20020SDTCD-000023']}</div>),/* 国际化处理： 角色或操作员*/
				dataIndex: 'm_memo',
				key: 'm_memo',
				width: '160px',
				render: (text, record, index) => (
					<div fieldid='m_memo'>
						{tableData[index].user && tableData[index].user.value ? (
							json['20020SDTCD-000012']/* 国际化处理： 用户*/
						) : tableData[index].role && tableData[index].role.value ? (
							json['20020SDTCD-000013']/* 国际化处理： 角色*/
						) : (
							emptyCell
						)}
					</div>
				)
			},
			{
				title: (<div fieldid='opr'>{json['20020SDTCD-000024']}</div>),/* 国际化处理： 操作*/
				dataIndex: 'm_memo',
				key: 'm_memo',
				width: '160px',
				render: (text, record, index) => (
					<div className="opration-wrapper" fieldid='opr'>
						{this.props.addStatus ? (
							emptyCell
						) : (
							<a className="row-edit-option" onClick={this.handleDel.bind(this, index)}>
								{json['20020SDTCD-000004']}{/* 国际化处理： 删除*/}
							</a>
						)}
					</div>
				)
			}
		];
		return columns
	}
	componentWillReceiveProps(nextProps) {
		let loCalData = nextProps.mainData;
		let pk_accountingbook = nextProps.accountingbook;
		let checkedArray = [];
		for (let i = 0, len = loCalData.length; i < len; i++) {
			loCalData[i].key = i;
			checkedArray.push(false);
		}
		this.setState({
			tableData: loCalData,
			pk_accountingbook: pk_accountingbook,
			checkedArray
		});
	}

	getCheckedData = () => {
		let { checkedData, checkedArray, tableData } = this.state;
		checkedData = [];
		for (var i = 0; i < checkedArray.length; i++) {
			if (checkedArray[i] === true) {
				checkedData.push(tableData[i].key);
			}
		}
		this.setState({
			checkedData
		});
		return checkedData;
	};
	resetCheckedData = (tableData) => {
		let checkedArray = [];
		for (let i = 0, len = tableData.length; i < len; i++) {
			tableData[i].key = i;
			checkedArray.push(false);
		}
		this.setState({
			checkedArray,
			checkedData: []
		});
	}

	//全选
	onAllCheckChange = () => {
		let self = this;
		let checkedArray = [];
		for (var i = 0; i < self.state.checkedArray.length; i++) {
			checkedArray[i] = !self.state.checkedAll;
		}
		self.setState({
			checkedAll: !self.state.checkedAll,
			checkedArray: checkedArray
		});
	};
	//单选
	onCheckboxChange = (text, record, index) => {
		let self = this;
		let allFlag = false;
		let checkedArray = self.state.checkedArray.concat();
		checkedArray[index] = !self.state.checkedArray[index];
		for (var i = 0; i < self.state.checkedArray.length; i++) {
			if (!checkedArray[i]) {
				allFlag = false;
				break;
			} else {
				allFlag = true;
			}
		}
		self.setState({
			checkedAll: allFlag,
			checkedArray: checkedArray
		});
	};
	renderColumnsMultiSelect(columns) {
		const { checkedArray } = this.state;
		const { multiSelect } = this.props;
		let indeterminate_bool = false;
		// let indeterminate_bool1 = true;
		if (multiSelect && multiSelect.type === 'checkbox') {
			let i = checkedArray.length;
			while (i--) {
				if (checkedArray[i]) {
					indeterminate_bool = true;
					break;
				}
			}
			let defaultColumns = [
				{
					title: (
						<div fieldid='firstcol'>
							<Checkbox
								className="table-checkbox"
								checked={this.state.checkedAll}
								indeterminate={indeterminate_bool && !this.state.checkedAll}
								onChange={this.onAllCheckChange}
							/>
						</div>	
					),
					key: 'checkbox',
					attrcode: 'checkbox',
                    dataIndex: 'checkbox',
					width: '60px',
					render: (text, record, index) => {
						return (
							<div fieldid='firstcol'>
								<Checkbox
									className="table-checkbox"
									checked={this.state.checkedArray[index]}
									onChange={this.onCheckboxChange.bind(this, text, record, index)}
								/>
							</div>
						);
					}
				}
			];
			columns = defaultColumns.concat(columns);
		}
		return columns;
	}
	createCfg(id, param) {
		var obj = {
			value: this.state.configs[id] ? this.state.configs[id].value : [],
			onChange: function(val) {
				var temp = Object.assign(this.state.configs[id], { value: val });
				this.setState(Object.assign(this.state.configs, temp));
			}.bind(this)
		};
		this.state.configs[id] = obj;
		var result_param = Object.assign(obj, param);
		return result_param;
	}
	handleAdd = () => {
		//新增
		let { tableData, checkedArray }= this.state;
		let obj = {
			key: tableData.length,
			iscorppublic: 'N',
			pk_transsort: '',
			user: {
				display: '',
				value: '',
				nodeType: ''
			},
			role: {
				display: '',
				value: '',
				nodeType: ''
			},
			code: '',
			pk_transperm: '',
			pk_busiunit: ''
		};
		tableData.push(Object.assign({}, obj));
		checkedArray.push(false)
		this.setState({
			tableData,
			checkedArray
		});
	};
	handleDel = (index) => {
		//删除
		let { tableData } = this.state;
		let checkedData = this.getCheckedData()
		if (typeof index == 'number') {
			tableData.splice(index, 1);
		} else if (checkedData.length > 0) {
			for (let i = tableData.length - 1; i >= 0; i--) {
				if(checkedData.includes(tableData[i].key)){
					tableData.splice(i, 1);
					continue;
				}
			}
		}
		this.setState({
			tableData
		},()=>{
			this.resetCheckedData(this.state.tableData);
		});
	};

	componentWillMount() {
		let callback= (json) =>{			
			this.setState({
				json:json,
			},()=>{		  
				// initTemplate.call(this, this.props);
				this.updataTableButtonStatus(false);
			})
		}
		getMultiLang({moduleId:'20020SDTCD',domainName:'gl',currentLocale:'simpchn',callback});
	}
	componentDidMount() {
		this.props.SelfDocTableRef(this);
	}
	updataTableButtonStatus = (visible) => {
		this.props.button.setButtonVisible([ 'add_line', 'del_line' ], visible);
	};

	render() {
		let { tableData, json } = this.state;
		let columns = this.renderColumnsMultiSelect(this.getColumns(json));
		return (
			<div>
				<NCDiv areaCode={NCDiv.config.TABS} className='header table-header'>
					<h4 className="title" fieldid={`${this.state.json['20020SDTCD-000025']}_title`}>
			 			{this.state.json['20020SDTCD-000025']}
			 		</h4>
					<div className='btn-group table-button-type'>
						{this.props.button.createButtonApp({
							area: 'table_header',
							onButtonClick: onButtonClick.bind(this),
							popContainer: document.querySelector('.table_header-button-area')
						})}
					</div>
				</NCDiv>
				<NCDiv fieldid='transfergroup' areaCode={NCDiv.config.TableCom}>
					<Table columns={columns} data={tableData} />
				</NCDiv>
			</div>
			// <Table
			// 	columns={columns}
			// 	data={tableData}
			// 	title={(currentData) => [
			// 		<h4 className="title" fieldid={`${this.state.json['20020SDTCD-000025']}_title`}>
			// 			{this.state.json['20020SDTCD-000025']}
			// 		</h4>,
			// 		<div className="btn-group">
			// 			{this.props.button.createButtonApp({
			// 				area: 'table_header',
			// 				onButtonClick: onButtonClick.bind(this),
			// 				popContainer: document.querySelector('.table_header-button-area')
			// 			})}
			// 		</div>
			// 	]}
			// />
		);
	}
}

// SelfDocTable = createPage({
// 	// initTemplate: initTemplate
// 	// mutiLangCode: '2052'
// })(SelfDocTable);
export default SelfDocTable;

SelfDocTable.defaultProps = {
	prefixCls: 'bee-table',
	multiSelect: {
		type: 'checkbox',
		param: 'key'
	}
};
